package validators;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.component.UIInput;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;

import dataStorage.DBData;

import beans.RegisterBean;
import beans.User;

public class NameValidator implements Validator {

	@Override
	public void validate(FacesContext context, UIComponent arg1, Object value) throws ValidatorException {
		String name = (String) value;
		
		String regex = "[A-Za-z0-9]+";
		if (!name.matches(regex)){
			FacesMessage fm = new FacesMessage("Username must contain only A-Z, a-z, 0-9");
			
			fm.setSeverity(FacesMessage.SEVERITY_ERROR);
			FacesContext facesCtx = FacesContext.getCurrentInstance();
			ExternalContext extCtx = facesCtx.getExternalContext();
			RegisterBean u = (RegisterBean)extCtx.getSessionMap().get("regBean");
			u.setMessage("");
			
			throw new ValidatorException(fm);
		}
		
		Connection conn = null;
		try {
			conn = DBData.getConnection();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		String valQuery = "SELECT UNAM FROM ZUSER WHERE (UNAM = '" + name + "')";
		try {
			PreparedStatement ps = conn.prepareStatement(valQuery);
			ResultSet rs = ps.executeQuery();
			if (rs.first()){
				String message = "ERROR: Username already exists";
				FacesMessage fm = new FacesMessage(FacesMessage.SEVERITY_ERROR, message, message);
				RegisterBean rba=(RegisterBean) DBData.getSessionBean("regBean");
				rba.setMessage("");
				
				throw new ValidatorException(fm);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

}
